package cn.ljy.authority.exception;

import cn.ljy.authority.utils.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseDTO<?> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return ResponseDTO.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public ResponseDTO<?> handleBindException(BindException e) {
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error("参数绑定异常: {}", message);
        return ResponseDTO.error(400, message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseDTO<?> handleConstraintViolationException(ConstraintViolationException e) {
        String message = e.getConstraintViolations().iterator().next().getMessage();
        log.error("参数校验异常: {}", message);
        return ResponseDTO.error(400, message);
    }

    @ExceptionHandler(Exception.class)
    public ResponseDTO<?> handleException(Exception e) {
        log.error("系统异常: ", e);
        return ResponseDTO.error(500, "系统繁忙，请稍后重试");
    }
}